15.3 Red-Black Trees
A Red-Black Tree is a self-balancing binary search tree (see Figure 15-10). It achieves approximate balance by adding a storage bit to each node representing its "color" (either red or black), combined with a series of mandatory constraint rules that ensure no single path from the root to a leaf is more than twice as long as any other.
Figure 15-10 Red-Black Tree
A red-black tree must strictly adhere to the following five properties; otherwise, it is not a valid red-black tree:
-
Every node is either red or black.
-
The root node must be black.
-
All leaf nodes (NIL nodes, which are empty nodes) are black.
-
If a node is red, then its child nodes must be black (meaning two consecutive red nodes are forbidden).
-
All paths from any given node to its matching leaf nodes must contain the exact same number of black nodes.
The red-black tree achieves an excellent trade-off between its balancing precision and structural manipulation overhead:
-
In both average and worst-case scenarios, the time complexity for lookup, insertion, and deletion operations evaluates to $O(log n)$.
-
Compared to strictly balanced AVL trees, red-black trees require fewer rotation operations, which yields superior performance in scenarios involving frequent insertions and deletions.
When an insertion or deletion violates any of the properties, the red-black tree restores its structural balance via the following remedies:
-
Color Flipping: Changing the red or black status of the nodes.
-
Left Rotation: Rotating the node to the left, causing its right child to become the new parent node.
-
Right Rotation: Rotating the node to the left, causing its left child to become the new parent node.
Within the Linux kernel, the red-black tree (rbtree) acts as a highly critical, high-performance self-balancing binary search tree. It is widely deployed across core subsystems including virtual memory management, process scheduling, and I/O monitoring. It has undergone deep optimizations tailored for kernel environments, setting its architecture significantly apart from textbook implementations.
The rbtree implementation within Linux (hosted within lib/rbtree.c) pursues extreme execution throughput and memory utilization efficiency via the following paradigms:
-
No Indirection Layer: Distinct from traditional paradigms where "the tree contains the payload data," Linux adopts an architecture where "the payload data embeds the tree node." Each struct rb_node is directly embedded within its target parent data structure. This eliminates supplemental memory allocations and pointer indirections, which dramatically elevates CPU cache hit rates.
-
Pointer Pointer-Packing Trick: To minimize the storage footprint, Linux compresses the node's color metadata into the lower bits of the parent node pointer (since memory pointers are always hardware-aligned, the least significant bits are naturally 0). This optimization saves 8 bytes of space per node on 64-bit systems.
-
No Built-in Search Callbacks: The kernel does not supply a unified comparison handler function. Instead, users write custom search and insertion logic tailored to specific key types (such as process IDs or virtual memory addresses), which completely eliminates function call overheads.
Furthermore, Augmented Red-Black Trees (augmented rbtree) support storing accumulated statistics (such as the maximum value within a sub-tree) inside the individual nodes. This capability is useful for implementing Interval Trees, which are deployed to handle overlap detection during virtual memory region management.
The red-black tree serves as the backbone for multiple time-sensitive tasks within the Linux kernel:
-
Completely Fair Scheduler (CFS): CFS leverages an rbtree to manage all runnable processes. The search key used within this tree is the process's vruntime (virtual runtime). The scheduler can continuously insert a new process at an $O(log n)$ execution cost and quickly locate the process that demands the CPU most urgently.
-
Virtual Memory Management (VMA): The kernel utilizes red-black trees to track every single vm_area_struct (memory segment) belonging to a process. When a page fault exception manifests, the kernel traverses the red-black tree to resolve the corresponding memory region within an $O(log n)$ time window.
-
epoll Subsystem: The epoll engine implements an rbtree to manage all file descriptors (FDs) monitored by user space. Even when monitoring tens of thousands of active connections, operations to add, delete, or modify an FD consistently maintain stable logarithmic complexity.
-
High-Resolution Timers (hrtimers): All pending timer requests are sorted by their precise expiration timestamps and stored within a red-black tree, guaranteeing that the system can process massive volumes of timed tasks both accurately and efficiently.